package ShapeModel;

import RuntimeInfo.State;

import javax.xml.stream.events.StartDocument;
import java.awt.*;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

public class CADLine extends Line2D.Double implements CADShape {
    private int zVal = 5;
    private Color c = Color.BLACK;
    private float strokeWidth = 1.0f;
    private boolean isTopDown; // 0代表斜向下，1代表斜向上

    public CADLine(double x1, double y1, double x2, double y2) {
        super(x1, y1, x2, y2);
    }

    public CADLine(double x1, double y1, double x2, double y2, int zVal, Color c, float strokeWidth) {
        super(x1, y1, x2, y2);
        this.zVal = zVal;
        this.c = c;
        this.strokeWidth = strokeWidth;
    }

    // part1: 实现CADShape定义的方法

    @Override
    public void setZ(int z) {
        this.zVal = z;
    }

    @Override
    public int getZ() {
        return zVal;
    }

    @Override
    public void setPos(Point2D start, Point2D end) {
        if (State.cursorState==State.CREATE) {
            if (start.getY() < end.getY()&&start.getX()<end.getX()||
                    start.getY() > end.getY()&&start.getX()>end.getX()) isTopDown = true;
            else isTopDown = false;
            setLine(start, end);
        } else {

            // 如果方向错误，予以改正
            if (isTopDown&&start.getY() > end.getY()||!isTopDown&&start.getY() <= end.getY()) {
                double t = start.getY();
                start.setLocation(start.getX(),end.getY());
                end.setLocation(end.getX(),t);
            }

            setLine(start,end);
        }

    }


    @Override
    // 重写resize方法，保证正确的方向
    public void resize(double dtop, double dbot, double dleft, double dright) {
        Rectangle2D bound = getBounds2D();
        setPos(bound.getMinX() + dleft, bound.getMinY() + dtop, bound.getMaxX() + dright, bound.getMaxY() + dbot);
        if(bound.getMinY() >= bound.getMaxY()||bound.getMinX() >= bound.getMaxX()) isTopDown=!isTopDown;
    }

    @Override
    public void setColor(Color c) {
        this.c = c;
    }

    @Override
    public Color getColor() {
        return this.c;
    }

    @Override
    public void setStrokeWidth(float width) {
        this.strokeWidth = width;
    }

    @Override
    public float getStrokeWidth() {
        return this.strokeWidth;
    }


    @Override
    public double getX() {
        return getX1();
    }

    @Override
    public double getY() {
        return getY1();
    }


    @Override
    // 需要进一步改进
    public boolean contains(Point2D p) {
        double xMax = Math.max(getX1(), getX2()), yMax = Math.max(getY1(), getY2());
        double xMin = Math.min(getX1(), getX2()), yMin = Math.min(getY1(), getY2());
        return p.getX() > xMin && p.getX() <= xMax && p.getY() >= yMin && p.getY() <= yMax;
    }
}
